package com.wp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wp.dao.PermissionDao;
import com.wp.dao.UserDao;
import com.wp.entity.MyUser;
import com.wp.entity.Permission;
import com.wp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.time.Period;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: WangPeng
 * @createTime: 2023/01/03 11:23
 * @description:
 * @version: v1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        QueryWrapper<MyUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        MyUser myUser = userDao.selectOne(queryWrapper);
        if (myUser != null){
            //查询该用户具有的权限
            List<Permission> permissions = permissionDao.findByUserId(myUser.getUserId());

            //返回UserDetails对象---它是一个接口，返回它的实现类。
            /* String username,账户
             * String password,密码数据库中的密码
             * 	Collection<? extends GrantedAuthority> authorities: 该用户具有的权限 */
            Collection<SimpleGrantedAuthority> authorities = permissions.stream().map(item -> new SimpleGrantedAuthority(item.getPerCode())).collect(Collectors.toList());
            User user = new User(username, myUser.getUserPassword(),authorities);
            return user;
        }
        return null;
    }
}
